﻿namespace CNVP.Framework.URLRewriter.Config
{
    using System;
    using System.IO;
    using System.Web;
    using System.Web.Caching;
    using System.Xml.Serialization;

    [Serializable, XmlRoot("RewriterConfig")]
    public class RewriterConfiguration
    {
        private RewriterRuleCollection rules;

        public static RewriterConfiguration GetConfig()
        {
            RewriterConfiguration configuration = HttpContext.Current.Cache["RewriterConfig"] as RewriterConfiguration;
            if (configuration != null)
            {
                return configuration;
            }
            string path = string.Empty;
            if (HttpContext.Current != null)
            {
                path = HttpContext.Current.Server.MapPath("~/") + @"\Config\SiteUrls.config";
            }
            else
            {
                path = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + @"\Config\SiteUrls.config";
            }
            if (!File.Exists(path))
            {
                return configuration;
            }
            XmlSerializer serializer = new XmlSerializer(typeof(RewriterConfiguration));
            using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    configuration = serializer.Deserialize(reader) as RewriterConfiguration;
                    CacheDependency dependencies = new CacheDependency(path);
                    HttpContext.Current.Cache.Insert("RewriterConfig", configuration, dependencies, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.AboveNormal, null);
                    return configuration;
                }
            }
        }

        public RewriterRuleCollection Rules
        {
            get
            {
                return this.rules;
            }
            set
            {
                this.rules = value;
            }
        }
    }
}

